package com.example.blogback.controller;

import com.example.blogback.dto.ApiResponse;
import com.example.blogback.dto.LoginRequest;
import com.example.blogback.dto.LoginResponse;
import com.example.blogback.dto.SendResetCodeRequest;
import com.example.blogback.dto.ResetPasswordRequest;
import com.example.blogback.entity.User;
import com.example.blogback.service.UserService;
import com.example.blogback.utils.JwtUtils;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.core.userdetails.UserDetails;
import jakarta.annotation.Resource;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UserService userService;

    @PostMapping("/login")
    public ApiResponse<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                ));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtils.generateToken((UserDetails) authentication.getPrincipal());

        User user = userService.findByUsername(loginRequest.getUsername());
        
        LoginResponse response = new LoginResponse(
                jwt,
                "Bearer",
                86400000L,
                user.getUsername(),
                user.getAvatar()
        );

        return ApiResponse.success(response);
    }

    @PostMapping("/forgot-password/code")
    public ApiResponse<String> sendResetPasswordCode(@Valid @RequestBody SendResetCodeRequest request) {
        userService.sendResetPasswordCode(request.getUsername());
        return ApiResponse.success("验证码已发送到您的邮箱");
    }

    @PostMapping("/forgot-password/reset")
    public ApiResponse<String> resetPassword(@Valid @RequestBody ResetPasswordRequest request) {
        userService.resetPassword(request.getUsername(), request.getCode(), request.getNewPassword());
        return ApiResponse.success("密码重置成功");
    }
}